package com.yzs.core.http

import android.content.Context
import com.blankj.utilcode.util.AppUtils
import com.franmontiel.persistentcookiejar.ClearableCookieJar
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.yzs.base.utils.LUtils
import com.yzs.core.momory.AppManager
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier

/**
 * author : yzs
 * time   : 2021/06/28
 * desc   : Retrofit 单例
 */
object RetrofitFactory {

    var mApplicationContext: Context? = null

    var DEFAULT_TIMEOUT = 15000L

    private val okHttpClientBuilder: OkHttpClient.Builder
        get() {
            val params = HttpsUtil.getSSLParams()
            val builder = OkHttpClient.Builder()
            builder.sslSocketFactory(params.sslSocketFactory, params.trustManager)
                .hostnameVerifier(HostnameVerifier { hostname, session -> true })
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .addInterceptor(getHeaderInterceptor())
//                .addInterceptor(ApiExceptionInterceptor())
                .addNetworkInterceptor(HttpLoggingInterceptor { message ->
                    if (AppUtils.isAppDebug()) LUtils.http(message)
                }.setLevel(HttpLoggingInterceptor.Level.BODY))
                .cookieJar(getCookie())
                .cache(getCache())

//            if (!SpUtils.decodeBoolean(C.SP.A_PROXY, false)) {
//                Log.i("测试工具", "禁止代理")
//                builder.proxy(Proxy.NO_PROXY)
//            }
            return builder
        }

    fun factory(): Retrofit {
        return Retrofit.Builder()
            .client(okHttpClientBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(AppManager.baseUrl)
            .build()
    }


    /**
     * 获取Header拦截器
     */
    private fun getHeaderInterceptor(): Interceptor {
        return HeaderInterceptor()
    }

    /**
     * 获取cookie持久化
     */
    private fun getCookie(): ClearableCookieJar {
        return PersistentCookieJar(
            SetCookieCache(),
            SharedPrefsCookiePersistor(mApplicationContext)
        )
    }

    /**
     * 获取缓存方式
     */
    private fun getCache(): Cache {
        // 缓存 100Mb
        return Cache(File(mApplicationContext?.cacheDir, "app_http_cache"), 1024L * 1024 * 100)
    }
}